package com.lou1052.redis.jedis.util;

import com.lou1052.core.serializer.Serializer;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 序列化选择器
 * 根据 Serializer的name属性匹配
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/10/31
 * Time: 21:46
 * To change this template use File | Settings | File Templates.
 */
public class SerSelector {
    /**
     * 默认序列化器
     */
    private final Serializer defaultSerializer;

    private final Map<String,Serializer> serializerMap;

    /**
     *
     * @param defaultSerializer
     * @param serializerSet
     */
    public SerSelector(Serializer defaultSerializer,Set<Serializer> serializerSet){
        this.defaultSerializer=defaultSerializer;
        Map<String,Serializer> mp = new HashMap<>();
        serializerSet.forEach((s)->{mp.put(s.name(),s);});
        if(!mp.containsKey(defaultSerializer.name())){
            mp.put(defaultSerializer.name(),defaultSerializer);
        }
        serializerMap=mp;
    }

    /**
     * 根据标识查找Serializer
     * @param key
     * @return
     */
    public Serializer select(String key){
        Serializer serializer = serializerMap.get(key);
        if(serializer==null){
            return defaultSerializer;
        }
        return serializer;
    }

    /**
     * Getter for property 'defaultSerializer'.
     *
     * @return Value for property 'defaultSerializer'.
     */
    public Serializer getDefaultSerializer() {
        return defaultSerializer;
    }
}
